package com.lenovo.lcdm.team.controller;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.lenovo.lcdm.common.enums.CommonMsgEnum;
import com.lenovo.lcdm.common.enums.ResponseMsgEnum;
import com.lenovo.lcdm.common.exception.BusinessException;
import com.lenovo.lcdm.common.model.ResponseVo;
import com.lenovo.lcdm.team.common.util.ContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;

@RequestMapping("login")
@RestController
public class LoginController {

    @Value("${spring.security.oauth2.client.provider.lcdm-oauth.token-uri}")
    private String url;

    @Value("${spring.security.oauth2.client.provider.lcdm-oauth.revoke-uri}")
    private String removeTokenUrl;

    @Value("${spring.security.oauth2.client.registration.oauth-client.client-id}")
    private String clientId;

    @Value("${spring.security.oauth2.client.registration.oauth-client.client-secret}")
    private String secret;

    @Value("${spring.security.oauth2.client.registration.oauth-client.authorization-grant-type}")
    private String grantType;

    @Value("${spring.security.oauth2.client.registration.oauth-client.scope}")
    private String scope;

    @PostMapping("login")
    public ResponseVo<String> login(@RequestParam String username, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new BusinessException("Parameters cannot be empty.", CommonMsgEnum.FAIL.getCode());
        }
        HttpResponse httpResponse = HttpUtil.createPost(url)
                .basicAuth(clientId, secret)
                .form("grant_type", "password")
                .form("username", username)
                .form("password", password)
                .form("scope", scope)
                .execute();
        if (httpResponse.getStatus() == 401) {
            return ResponseVo.error(ResponseMsgEnum.AUTH_ERROR);
        }
        return ResponseVo.success(httpResponse.body());
    }

    @GetMapping("removeToken")
    public void removeToken(HttpServletRequest request) {
        HttpResponse httpResponse = HttpUtil.createPost(removeTokenUrl).basicAuth(clientId, secret)
                .form("itcode", ContextUtil.getCurrentUser())
                .execute();
    }

    @PostMapping("basic/login")
    private ResponseVo<String> checkBasicAuthorization(HttpServletRequest request) {
        String rawStringAuthorization = request.getHeader("Authorization");
        if (!StringUtils.startsWith(rawStringAuthorization, "Basic")) {
            return ResponseVo.error(ResponseMsgEnum.AUTH_ERROR);
        }
        String base64StringAuthorization = StringUtils.replaceOnce(rawStringAuthorization, "Basic", "");
        base64StringAuthorization = StringUtils.trim(base64StringAuthorization);

        byte[] bytesAuthorization = Base64.getDecoder().decode(base64StringAuthorization);
        String stringAuthorization = new String(bytesAuthorization);

        String[] arrUserAndPass = StringUtils.split(stringAuthorization, ":");
        if (2==arrUserAndPass.length) {
            return ResponseVo.error(ResponseMsgEnum.AUTH_ERROR);
        }

        String username = arrUserAndPass[0];
        String password = arrUserAndPass[1];
        HttpResponse httpResponse = HttpUtil.createPost(url)
                .basicAuth(clientId, secret)
                .form("grant_type", "password")
                .form("username", username)
                .form("password", password)
                .form("scope", scope)
                .execute();

        if (httpResponse.getStatus() == 401) {
            return ResponseVo.error(ResponseMsgEnum.AUTH_ERROR);
        }
        return ResponseVo.success(httpResponse.body());
    }
}
